package com.algorithm.base.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 51. N 皇后
 * 测试小优化
 *
 * @author Amadeus
 * @date 2023/11/10
 */
public class SolveQueens {

    List<List<String>> result = new ArrayList<>();

    public List<List<String>> solveNQueens(int n) {
        char[][] chars = new char[n][n];
        for (char[] c : chars) {
            Arrays.fill(c, '.');
        }
        backtracking(0, n, chars);
        return result;
    }

    public void backtracking(int row, int n, char[][] chars) {
        if (row == n) {
            result.add(Array2List(chars));
            return;
        }
        for (int i = 0; i < n; i++) {
            if (isValid(i, row, n, chars)) {
                chars[i][row] = 'Q';
                backtracking(row + 1, n, chars);
                chars[i][row] = '.';
            }
        }
    }

    public boolean isValid(int i, int row, int n, char[][] chars) {
        //列判断
        for (int j = row; j >= 0; j--) {
            if (chars[i][j] == 'Q') {
                return false;
            }
        }
        //左上
        for (int j = i - 1, k = row - 1; j >= 0 && k >= 0; j--, k--) {
            if (chars[j][k] == 'Q') {
                return false;
            }
        }
        //右上
        for (int j = i + 1, k = row - 1; j < n && k >= 0; j++, k--) {
            if (chars[j][k] == 'Q') {
                return false;
            }
        }
        return true;
    }

    public List<String> Array2List(char[][] chessboard) {
        List<String> list = new ArrayList<>();
        for (char[] c : chessboard) {
            list.add(String.copyValueOf(c));
        }
        return list;
    }

}
